﻿// Range.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <ranges>
#include <vector>
#include <string>
#include <iomanip>
#include <httplib.h>
#include <json/json.h>

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>

using namespace std;

// 将十六进制字符转换为对应的整数值
int hexToInt(char hexDigit) {
	if (hexDigit >= '0' && hexDigit <= '9') {
		return hexDigit - '0';
	}
	else if (hexDigit >= 'A' && hexDigit <= 'F') {
		return hexDigit - 'A' + 10;
	}
	else if (hexDigit >= 'a' && hexDigit <= 'f') {
		return hexDigit - 'a' + 10;
	}
	return -1;
}

// 将十六进制字符串转换为二进制字符串（每一位十六进制对应4位二进制）
string hexToBinary(const string& hexStr) {
	string binaryStr;
	for (char hexChar : hexStr) {
		int hexValue = hexToInt(hexChar);
		string binValue = "";
		for (int i = 0; i < 4; ++i) {
			binValue = (hexValue & (1 << (3 - i))) ? "1" : "0";
			binaryStr += binValue;
		}
	}
	return binaryStr;
}

// 解析Hex文件的一行数据，提取其中的数据部分并转换为二进制
vector<string> parseHexLine(const string& hexLine) {
	vector<string> binaryData;
	if (hexLine[0] == ':') {
		int byteCount = hexToInt(hexLine[1]) * 16 + hexToInt(hexLine[2]);
		int dataStart = 9;
		int dataEnd = dataStart + byteCount * 2;
		for (int i = dataStart; i < dataEnd; i += 2) {
			string hexDataSegment = hexLine.substr(i, 2);
			string binarySegment = hexToBinary(hexDataSegment);
			binaryData.push_back(binarySegment);
		}
	}
	return binaryData;
}

// 主函数，执行Hex文件到Bin文件的转换
void hexToBin(const string& hexFilePath, const string& binFilePath) {
	ifstream hexFile(hexFilePath, ios::in);
	ofstream binFile(binFilePath, ios::out | ios::binary);
	if (!hexFile) {
		cerr << "无法打开Hex文件" << endl;
		return;
	}
	if (!binFile) {
		cerr << "无法打开或创建Bin文件" << endl;
		return;
	}
	string line;
	vector<string> allBinaryData;
	while (getline(hexFile, line)) {
		vector<string> binaryData = parseHexLine(line);
		allBinaryData.insert(allBinaryData.end(), binaryData.begin(), binaryData.end());
	}
	string binaryStr;
	for (const string& binPart : allBinaryData) {
		binaryStr += binPart;
	}
	int binaryLength = binaryStr.length();
	// 将二进制字符串转换为字节数组并写入Bin文件
	for (int i = 0; i < binaryLength; i += 8) {
		string byteStr = binaryStr.substr(i, 8);
		char byteValue = (char)stoi(byteStr, nullptr, 2);
		binFile.write(&byteValue, 1);
	}
	hexFile.close();
	binFile.close();
}

struct Product {
	int quantity;
	int weight;
};
struct Result {
	int minCount;
	vector<int> productCounts;
};

Result minProductsToAchieveWeight(const vector<Product>& products, double targetWeight) {
	int n = products.size();
	vector<int> dp(static_cast<int>(targetWeight * 100) + 1, INT_MAX);
	vector<vector<int>> productUsage(static_cast<int>(targetWeight * 100) + 1, vector<int>(n, 0));
	dp[0] = 0;

	for (int k = 0; k < n; ++k) {
		int weight = static_cast<int>(products[k].weight * 100);
		for (int i = 0; i < products[k].quantity; ++i) {
			for (int j = dp.size() - 1; j >= weight; --j) {
				if (dp[j - weight] != INT_MAX && dp[j - weight] + 1 < dp[j]) {
					dp[j] = dp[j - weight] + 1;
					productUsage[j] = productUsage[j - weight];
					productUsage[j][k]++;
				}
			}
		}
	}

	int resultWeight = static_cast<int>(targetWeight * 100);
	Result result;
	result.minCount = dp[resultWeight] == INT_MAX ? -1 : dp[resultWeight];
	result.productCounts = dp[resultWeight] == INT_MAX ? vector<int>(n, 0) : productUsage[resultWeight];
	return result;
}
#include <chrono>
using namespace std;
using namespace std::chrono;



/****************************Info**********************************************
 * Name:    CRC-8 1D              x8+x4+x3+x2+1
 * Width:        8
 * Poly:    0x00
 * Init:    0x00
 * Refin:   False
 * Refout:  False
 * Xorout:  0x00
 * Note:
 *****************************************************************************/
const static unsigned char l_e2eTable_CRC_ub[256] =
{
	0x00, 0x1D, 0x3A, 0x27, 0x74, 0x69, 0x4E, 0x53,
	0xE8, 0xF5, 0xD2, 0xCF, 0x9C, 0x81, 0xA6, 0xBB,
	0xCD, 0xD0, 0xF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 0x7B, 0x66,
	0xDD, 0xC0, 0xE7, 0xFA, 0xA9, 0xB4, 0x93, 0x8E,
	0xF8, 0xE5, 0xC2, 0xDF, 0x8C, 0x91, 0xB6, 0xAB,
	0x10, 0x0D, 0x2A, 0x37, 0x64, 0x79, 0x5E, 0x43,
	0xB2, 0xAF, 0x88, 0x95, 0xC6, 0xDB, 0xFC, 0xE1,
	0x5A, 0x47, 0x60, 0x7D, 0x2E, 0x33, 0x14, 0x09,
	0x7F, 0x62, 0x45, 0x58, 0x0B, 0x16, 0x31, 0x2C,
	0x97, 0x8A, 0xAD, 0xB0, 0xE3, 0xFE, 0xD9, 0xC4 };


static unsigned char Crc8(const unsigned char* data, unsigned long datalen)
{

	/* Start value as required */
	unsigned char t_Crc_ub = 0x0;
	unsigned char t_temp_ub = 0x0;

	for (unsigned long t_ArrayIdx_ul = 0; t_ArrayIdx_ul < datalen; t_ArrayIdx_ul++) {
		t_temp_ub = *(data + t_ArrayIdx_ul);
		t_Crc_ub = l_e2eTable_CRC_ub[t_temp_ub ^ t_Crc_ub & 0xFF];
	}

	return t_Crc_ub;

}

std::mutex muxList[9999];
int Lock(int i, int onoff)
{
	if (i < 0)
		return 0;

	if (onoff == 1)
	{
		if (!muxList[i].try_lock())
			return 0;
		return 1;
	}
	else if (onoff == 0)
	{
		if (muxList[i].try_lock())
		{
			muxList[i].unlock();
			return 1;
		}
		return 1;
	}
	return 0;
}

#include <opencv2/opencv.hpp>
int main()
{
	// chufeng
	std::string filePath = "D:\\Desktop\\鱼眼箱四种组合分布图\\0.bmp";
	cv::Mat img = cv::imread(filePath);
	if (img.empty())
	{
		std::cout << "图片读取失败" << std::endl;
		return -1;
	}

	cv::imshow("img", img);

	//Lock(0, 1);
	
	/*cv::VideoCapture cap;
	cap.open(1);

	if (!cap.isOpened())
	{
		std::cout << "摄像头打开失败" << std::endl;
		return -1;
	}

	cv::Mat frame;
	while (1)
	{
		cap >> frame;
		if (frame.empty())
		{
			std::cout << "摄像头读取失败" << std::endl;
			break;
		}
		cv::imshow("frame", frame);
		if (cv::waitKey(30) == 27)
		{
			break;
		}
	}*/





	return 0;
	unsigned char data[] = { 0x05,0x06,0x66,0x00,0x00,0x00,0x00 };
	Crc8(data, 7);

	// 生成50个产品，重量和数量随机
	vector<Product> products;
	random_device rd;
	mt19937 gen(rd());
	uniform_int_distribution<> weightDis(1, 10); // 假设产品重量在1到10之间
	uniform_int_distribution<> quantityDis(1, 5); // 假设产品数量在1到10之间

	for (int i = 0; i < 50; ++i) {
		products.push_back({ quantityDis(gen), weightDis(gen) });
	}

	int targetWeight = 200; // 目标重量
	auto start = high_resolution_clock::now();
	Result result = minProductsToAchieveWeight(products, targetWeight);
	auto end = high_resolution_clock::now();
	auto duration = duration_cast<milliseconds>(end - start);
	cout << "生成随机产品耗时: " << duration.count() << " 毫秒" << endl;
	if (result.minCount != -1) {
		cout << "最少需要 " << result.minCount << " 个产品来达到指定的重量。" << endl;
		cout << "使用的产品数量如下：" << endl;
		for (size_t i = 0; i < products.size(); ++i) {
			cout << "产品 " << i + 1 << " (重量: " << products[i].weight << "): " << result.productCounts[i] << " 个" << endl;
		}
	}
	else {
		cout << "无法达到指定的重量。" << endl;
	}









	return 0;
	string hexFilePath = "D:\\Desktop\\1.hex";  // 替换为实际的Hex文件路径
	string binFilePath = "D:\\Desktop\\output.bin";  // 替换为要生成的Bin文件路径
	hexToBin(hexFilePath, binFilePath);
	return 0;

	// 用httplib写一个服务器
	httplib::Server svr;
	svr.set_base_dir("./");
	svr.Get("/hi", [](const httplib::Request& req, httplib::Response& res)
		{
			std::string str = "{""key"":""value""}";
			res.set_content(str, "text/plain");
		});

	svr.Post("/post", [](const httplib::Request& req, httplib::Response& res)
		{
			std::string str = "{""key"":""value1111""}";
			res.set_content(str, "application/json");
		});

	svr.listen("localhost", 1234);


	//{
	//	std::vector<int> as{ 1,2,3,4 };
	//	auto p = as
	//		| std::views::filter([](int a)
	//			{
	//				return a > 2;
	//			})
	//		| std::views::transform([](int a) {return a * a; });
	//
	//	for (const auto& item : p)
	//	{
	//		std::cout << item << " ";
	//	}
	//
	//
	//
	//	std::string str = "chufeng@25@11000,chufeng@25@11000";
	//	auto v = str | std::views::split('@') | std::views::transform([](auto word) {return std::string(word.begin(), word.end()); });
	//	std::vector<std::string> words(v.begin(), v.end());
	//
	//
	//	auto s = str | std::views::split('@') | std::views::transform([](auto w) {return std::string(w.begin(), w.end()); });
}